use crossterm::{
    event::{self, Event},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::{
    io,
    time::Duration,
};
use tui::{
    backend::CrosstermBackend,
    layout::Rect,
    style::Style,
    widgets::{Block, Borders, Paragraph},
    Terminal,
};

mod pet_anime;
mod pet_action;
mod pet_config;

use pet_anime::PetAnimationManager;
use pet_action::PetAction;
use pet_config::{PetConfig, PetType};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 加载或创建配置文件
    let config = PetConfig::load_or_create()?;
    
    // 设置终端
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // 初始化宠物动画和动作系统
    let pet_type = config.pet_type;
    let mut pet_animation = PetAnimationManager::new(pet_type);
    let mut pet_action = PetAction::new(config);
    
    // 向后兼容：如果配置中有旧的breed字段，迁移到新的pet_type
    if let Some(breed) = pet_action.get_config().breed {
        let new_pet_type = PetType::Cat(breed);
        pet_action.get_config_mut().pet_type = new_pet_type;
        pet_action.get_config_mut().breed = None;
        let _ = pet_action.get_config().save(); // 保存迁移后的配置
    }

    loop {
        // 更新状态
        {
            let config = pet_action.get_config_mut();
            config.update_time_decay();
            config.force_check_sleep_state();
        }
        
        // 获取状态信息
        let is_sleeping = pet_action.get_config_mut().status.is_sleeping;
        let can_move = pet_action.get_config_mut().can_move();
        // let mood = pet_action.get_config_mut().get_mood().to_string(); // 不再需要
        let status_text = pet_action.get_status();
        
        // 检查宠物是否真正在移动
        let is_actually_moving = pet_animation.is_moving();
        
        // 获取当前心情状态
        let mood_state = pet_action.get_config().get_mood_state();
        
        // 更新动画，传入移动、睡眠和心情状态
        pet_animation.update(can_move, is_sleeping, mood_state);
        
        terminal.draw(|f| {
            let size = f.size();
            
            // 获取当前动画帧
            let current_pet = if is_sleeping {
                // 睡眠状态使用睡眠帧
                pet_animation.get_sleep_frame()
            } else if pet_animation.is_crying() {
                // 哭泣状态优先显示哭泣动画
                pet_animation.get_current_frame().clone()
            } else {
                // 其他状态都使用正常动画帧（包括移动和静止）
                // 章鱼的表情会根据心情在动画帧中体现
                pet_animation.get_current_frame().clone()
            };
            
            let (pet_x, pet_y) = pet_animation.get_position();
            
            // 计算输出框位置（屏幕下方三分之一处）
            let output_y = size.height - (size.height / 3);
            
            // 确保宠物不会跑出屏幕边界，且不会移动到输出区域下方
            let safe_x = pet_x.min(size.width.saturating_sub(17));
            let safe_y = pet_y.min((output_y - 1).saturating_sub(6));
            
            // 渲染宠物
            for (i, frame) in current_pet.iter().enumerate() {
                let frame_y = safe_y + i as u16;
                // 确保不会渲染到屏幕外或输出区域
                if frame_y < output_y.saturating_sub(1) && frame_y < size.height {
                    let style = if let Some(color) = frame.color {
                        Style::default().fg(color)
                    } else {
                        Style::default()
                    };
                    let paragraph = Paragraph::new(frame.text.as_str())
                        .style(style)
                        .block(Block::default().borders(Borders::NONE));
                    f.render_widget(paragraph, 
                        Rect::new(safe_x, frame_y, 15, 1));
                }
            }
            
            // 渲染状态信息
            let status = Paragraph::new(status_text.clone())
                .block(Block::default().borders(Borders::NONE));
            f.render_widget(status, 
                Rect::new(0, 0, size.width, 1));
            
            // 渲染输出框
            let output_block = Block::default()
                .borders(Borders::ALL)
                .title("Output");
            let output_area = Rect::new(2, output_y, size.width - 4, 3);
            f.render_widget(output_block, output_area);
            
            // 渲染帮助信息
            let help = Paragraph::new(pet_action.get_help_text())
                .block(Block::default().borders(Borders::NONE));
            f.render_widget(help, 
                Rect::new(0, size.height - 1, size.width, 1));
        })?;

        // 处理用户输入（非阻塞）
        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                if !pet_action.handle_input(key.code, &mut pet_animation) {
                    break; // 用户选择退出
                }
            }
        }
        
        // 即使没有用户输入也要短暂等待，确保循环持续运行
        std::thread::sleep(Duration::from_millis(50));
    }

    // 保存配置并清理终端
    pet_action.get_config_mut().save()?;
    
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    Ok(())
}
